/*
 * Copyright (C) 2010 Fred Barrie This program is free software: you can
 * redistribute it and/or modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version. This program is distributed
 * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details. You should have received
 * a copy of the GNU General Public License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 */
package org.aergia.vinny.engine.servicetime;

import java.util.Calendar;
import java.util.logging.Logger;

import org.aergia.vinny.core.ApiResult;
import org.aergia.vinny.database.Database;
import org.aergia.vinny.database.pojo.Scan;
import org.aergia.vinny.database.pojo.Service;
import org.aergia.vinny.database.pojo.VinnyOption;
import org.aergia.vinny.util.DateUtil;

/**
 * @author fred
 */
public final class ClockTimeCalculator extends ServiceTimeCalculatorSkeleton {

	/**
	 * Default service time if the value is not set in the database.
	 */
	private static final int DEFAULT_SERVICE_TIME = 300;

	private final int defaultServiceTime;

	public ClockTimeCalculator(final Database database) {
		super(database, Logger.getLogger(ClockTimeCalculator.class.getCanonicalName()));
		this.defaultServiceTime = this.getDefaultServiceTime();
	}

	@Override
	protected Calendar getAppropriateEndTime(final Scan scan) {
		final Calendar closing = DateUtil.getInstance(scan.getScanTime());
		closing.set(Calendar.MINUTE, this.defaultServiceTime);
		return closing;
	}

	@Override
	protected boolean isInServiceTime(final Service service) {
		return DateUtil.isWithinMinutes(service.getStartTime(), service.getEndTime(), this.defaultServiceTime);
	}

	@Override
	protected boolean isScanOutOfRange(final Scan scan) {
		return DateUtil.isBeforeYesterday(scan.getScanTime());
	}

	@Override
	protected boolean isScanTimesOk(final Scan startScan, final Scan endScan) {
		return DateUtil.isWithin24Hours(startScan.getScanTime(), endScan.getScanTime());
	}

	private int getDefaultServiceTime() {
		int result = ClockTimeCalculator.DEFAULT_SERVICE_TIME;

		final ApiResult<VinnyOption> optionResult = this.database.getOption(VinnyOption.DEFAULT_SERVICE_TIME);
		if (!optionResult.isError()) {
			try {
				result = Integer.parseInt(optionResult.getResult().getValue());
			} catch (final NumberFormatException nfe) {
				// ignore
			}
		}
		return result;
	}
}
